<template>
  <el-card class="box-card" v-loading="loading">
    <div slot="header" class="clearfix">
      <span>信息嵌入</span>
    </div>
    <el-form
      label-width="120px"
      :rules="rules"
      ref="formLabelAlign"
      :model="formLabelAlign"
    >
      <el-form-item label="选择算法">
        <el-radio-group v-model="formLabelAlign.algorithm">
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="适用范围：如果想嵌入秘密信息，并且不影响载体图像的使用时可用该算法。可用于：版权保护、图像完整性验证、隐蔽传输和保护隐私信息。"
          >
            <el-button slot="reference">
              <el-radio label="1">明文图像可逆信息隐藏</el-radio>
            </el-button>
          </el-popover>
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="适用范围：不仅想嵌入秘密信息，而且还想保护载体图像的内容安全时使用该算法。可用于：云存储和隐私保护。"
          >
            <el-button slot="reference">
              <el-radio label="2">加密图像可逆信息隐藏</el-radio>
            </el-button>
          </el-popover>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择载体图片" prop="carrierImage" ref="carrierImage">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8888/user/upload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <div class="originimg" v-if="formLabelAlign.carrierImage" @click.stop>
            <img :src="formLabelAlign.carrierImage" alt="" class="avatar" />
            <div class="img-bg">
              <span @click.stop="remove">
                <i class="el-icon-delete"></i>
              </span>
            </div>
          </div>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="加密"
        prop="encrypt"
        v-if="formLabelAlign.algorithm === '2'"
      >
        <el-switch
          v-model="formLabelAlign.encrypt"
          active-color="#13ce66"
          @change="encryptImg"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="秘密信息" prop="secretData">
        <el-input
          v-model="formLabelAlign.secretData"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-form-item class="submitButton">
        <el-button type="primary" @click="submitForm('formLabelAlign')"
        >提交</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible" title="嵌入后的图像" center>
      <el-card class="el-cards">
        <div class="originimg">
          <img width="300px" :src="dialogImageUrl" alt="" />
          <div class="img-bg">
            <span @click="handleDownload()">
              <i class="el-icon-download"></i>
            </span>
          </div>
        </div>
      </el-card>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "Insert",
  data() {
    var encryptValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请先进行加密"));
      } else {
        callback();
      }
    };
    return {
      isEmbed: 0, //嵌入
      formLabelAlign: {
        algorithm: "1", //算法选择 1，2
        encrypt: false, // 是否加密
        carrierImage: "", //载体图像
        secretData: "", //秘密信息
      },
      containSecretImage: "", //载密图像
      imageKey: "", //图像密钥
      dataKey: "", //信息密钥
      encryptedImage: "", //加密图像
      carrierEncryptedImage: "", // 载密加密图像
      loading: false,
      dialogImageUrl: "", //嵌入后的图像
      dialogVisible: false, //嵌入后的图像弹窗
      disabled: false, //上传按钮是否禁用
      rules: {
        secretData: [
          { required: true, message: "请输入秘密信息", trigger: "blur" },
        ],
        encrypt: [{ validator: encryptValid, trigger: "change" }],
        carrierImage: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    const urlList = document.querySelector(".el-upload-list");
    console.log(urlList);
  },
  methods: {
    // 下载
    handleDownload() {
      const name = "嵌入后的图片";
      const url = this.formLabelAlign.carrierImage;
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        a.download = name;
        a.href = url;
        a.click();
      };
      image.src = url;
    },

    // 移除文件
    remove() {
      this.formLabelAlign.carrierImage = "";
    },
    // 上传文件
    handleAvatarSuccess(res, file, fileList) {
      if (res.url) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.formLabelAlign.carrierImage = res.url;
        this.oldCarrierImage = this.formLabelAlign.carrierImage
        this.$refs.carrierImage.clearValidate();
      }
    },
    // 加密图像
    encryptImg(val) {
      if (val) {
        console.log(this.formLabelAlign.carrierImage,"11111111111111111111111111111")
        this.loading = true;
        this.$axios
          .post("http://127.0.0.1:7777/encryption", {carrierImage:this.formLabelAlign.carrierImage},{responseType: 'blob'})
          .then((res) => {
            console.log(res,2222222)
            if (res.data) {
              let blob = new Blob([res.data], { type: res.headers['content-type']});
              // let url = URL.createObjectURL(blob);
              this.formLabelAlign.carrierImage = URL.createObjectURL(blob)

              var formData = new FormData();
              formData.append('file', blob, `${+new Date()}加密图片.png`);

              // 发送 HTTP POST 请求到 Java 服务
              fetch('http://localhost:8888/user/upload',{
                method: 'POST',
                body: formData
              }).then(response => response.json())
                .then(res => {
                  // 处理响应
                  console.log(res, '加密后的图像')
                  this.loading = false;
                  this.encryptedImage = res.url
                  console.log('File uploaded successfully');
                })
                .catch(error => {
                  // 处理错误
                  console.error('Error uploading file:', error);
                });

            }
          }).catch(err=>{
          this.loading = false
          this.$message.error('很抱歉！嵌入失败，请上传正确格式的的载体图像！')
        });
      }
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        const { carrierImage, secretData,encrypt } = this.formLabelAlign;
        if (valid) {
          this.loading = true;
          // 这里是调取算法
          this.$axios
            .post("http://127.0.0.1:7777/embed_data", {
              carrierImage: encrypt ? this.encryptedImage : carrierImage,
              secretData,
              isEncry: this.formLabelAlign.algorithm === '2' // 是否加密 1 不加密 2 加密
            },{responseType: 'blob'})
            .then((res) => {
              let blob = new Blob([res.data], { type: res.headers['content-type']});
              let url = URL.createObjectURL(blob);
              this.dialogImageUrl = url;
              // 创建一个 FormData 对象并将 Blob 对象添加到其中
              var formData = new FormData();
              formData.append('file', blob, `${+new Date()}载密图片.png`);

              // 发送 HTTP POST 请求到 Java 服务
              fetch('http://localhost:8888/user/upload',{
                method: 'POST',
                body: formData
              }).then(response => response.json())
                .then(res => {
                  // 处理响应
                  console.log(res, '处理后的图片.png')
                  this.containSecretImage = res.url
                  if (this.formLabelAlign.encrypt){
                    this.carrierEncryptedImage = res.url
                  }
                  this.loading = false;
                  this.$message({
                    message: "信息嵌入成功",
                    type: "success",
                  });
                  setTimeout(() => {
                    this.dialogVisible = true;
                    // this.dialogImageUrl = res.containSecretImage;
                  }, 1000);

                  let params = {
                    isEmbed: this.isEmbed,
                    carrierImage,
                    containSecretImage: this.containSecretImage,
                    secretData,
                  };
                  if (this.formLabelAlign.encrypt){
                      params = {
                      isEmbed: this.isEmbed,
                      carrierImage: this.oldCarrierImage,
                      encryptedImage:this.encryptedImage,
                      carrierEncryptedImage:this.carrierEncryptedImage,
                      secretData,
                    }
                  }
                  this.$axios
                    .post("http://localhost:8888/user/log", {
                      ...params,
                    })
                    .then((res) => {
                      // 这里是在算法回来后再次调用后端接口存起来
                      console.log(res, '存储成功')
                    });
                  console.log('File uploaded successfully');
                })
                .catch(error => {
                  // 处理错误
                  console.error('Error uploading file:', error);
                });
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.el-button {
  border: none;
}
.box-card {
  width: 700px;
  min-height: 550px;
  background: #fff;
  padding: 20px;
  border: 1px solid #ebebeb;
  position: relative;
  border-radius: 3px;
  box-shadow: 0 0 8px rgba(232, 237, 250, 0.6),
  0 2px 4px 0 rgba(232, 237, 250, 0.5);
}
.submitButton {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  margin-bottom: 0;
}
.clearfix {
  text-align: center;
  font-size: 24px;
  font-weight: 500;
}
/deep/ .el-dialog__body {
  text-align: center;
}

/deep/.el-cards .el-card__body {
  display: flex;
  align-items: center;
  flex-direction: column;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.originimg {
  position: relative;
}
.img-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-icon-delete,
.el-icon-download {
  display: none;
}
.img-bg:hover {
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.img-bg:hover .el-icon-delete,
.img-bg:hover .el-icon-download {
  display: block;
  font-size: 36px;
  color: #fff;
}
</style>
